package com.xhj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhj.entity.Chapter;
import com.xhj.entity.Video;
import com.xhj.mapper.ChapterMapper;
import com.xhj.service.ChapterService;
import com.xhj.service.VideoService;
import com.xhj.vo.ChapterVo;
import com.xhj.vo.VideoVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 课程(EduChapter)表服务实现类
 *
 * @author makejava
 * @since 2021-02-26 12:09:03
 */
@Service()
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper,Chapter> implements ChapterService {

    @Autowired
    private VideoService videoService;

    @Override
    public List<ChapterVo> chapterList(String courseId) {
        QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
        QueryWrapper<Video> videoQueryWrapper = new QueryWrapper<>();
        // 设置查询条件
        queryWrapper.eq("course_id",courseId);
        videoQueryWrapper.eq("course_id",courseId);
        List<Chapter> chapterList = this.list(queryWrapper);
        List<Video> videoList = videoService.list(videoQueryWrapper);
        // 判断是否有章节
        if(chapterList == null || chapterList.size() == 0) throw new RuntimeException("该课程没有章节！");

        List<ChapterVo> chapterVoList = new ArrayList<>();
        // 遍历chapterList
        for (Chapter chapter : chapterList) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(chapter,chapterVo);

            chapterVoList.add(chapterVo);

            List<VideoVo> videoVoList = new ArrayList<>();
            for (Video video : videoList) {
                if (video.getChapterId().equals(chapter.getId())){
                    VideoVo videoVo = new VideoVo();
                    BeanUtils.copyProperties(video,videoVo);
                    videoVoList.add(videoVo);
                }
            }
            chapterVo.setChildren(videoVoList);
        }
        return chapterVoList;
    }

    @Override
    public boolean deleteChapterById(String id) {
        // 根据courseId删除对应的video
        QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chapter_id",id);
        videoService.remove(queryWrapper);
        // 接着删除chapter
        return this.removeById(id);
    }
}